package com.nbsaas.boot;

import com.nbsaas.boot.api.adapter.RegistryAdapter;
import com.nbsaas.boot.api.adapter.ServiceInstance;
import com.tencent.polaris.api.core.ProviderAPI;
import com.tencent.polaris.api.rpc.InstanceRegisterRequest;
import com.tencent.polaris.api.rpc.InstanceDeregisterRequest;
import com.tencent.polaris.factory.api.DiscoveryAPIFactory;

public class PolarisRegistryAdapter implements RegistryAdapter {
    
    private ProviderAPI providerAPI;
    
    public PolarisRegistryAdapter() {
        this.providerAPI = DiscoveryAPIFactory.createProviderAPI();
    }
    
    @Override
    public void register(ServiceInstance instance) {
        try {
            InstanceRegisterRequest request = new InstanceRegisterRequest();
            
            // 设置实例所属服务信息
            request.setService(instance.getName());
            
            // 设置实例所属服务的命名空间信息
            String namespace = instance.getNamespace();
            if (namespace != null && !namespace.isEmpty()) {
                request.setNamespace(namespace);
            } else {
                request.setNamespace("default");
            }
            
            // 设置实例的 host 和 port 信息
            String host = instance.getHost();
            Integer port = instance.getPort();
            String protocol = instance.getProtocol();
            
            if (host != null) {
                request.setHost(host);
            }
            if (port != null) {
                request.setPort(port);
            }
            if (protocol != null) {
                request.setProtocol(protocol);
            }
            
            // 从metadata中获取其他配置信息
            if (instance.getMetadata() != null) {
                // 可选，资源访问Token
                String token = instance.getMetadata().get("token");
                if (token != null) {
                    request.setToken(token);
                }
                
                // 设置实例版本
                String version = instance.getMetadata().get("version");
                if (version != null) {
                    request.setVersion(version);
                }
                
                // 设置实例权重
                String weight = instance.getMetadata().get("weight");
                if (weight != null) {
                    request.setWeight(Integer.parseInt(weight));
                }
                
                // 设置实例地理位置 zone 信息
                String zone = instance.getMetadata().get("zone");
                if (zone != null) {
                    request.setZone(zone);
                }
                
                // 设置实例地理位置 region 信息
                String region = instance.getMetadata().get("region");
                if (region != null) {
                    request.setRegion(region);
                }
                
                // 设置实例地理位置 campus 信息
                String campus = instance.getMetadata().get("campus");
                if (campus != null) {
                    request.setCampus(campus);
                }
                
                // 设置心跳健康检查ttl
                String ttl = instance.getMetadata().get("ttl");
                if (ttl != null) {
                    request.setTtl(Integer.parseInt(ttl));
                } else {
                    // 默认5秒
                    request.setTtl(5);
                }
                
                // 设置实例的标签
                request.setMetadata(instance.getMetadata());
            }
            
            // 执行注册
            providerAPI.register(request);
            
        } catch (Exception e) {
            throw new RuntimeException("Failed to register service instance", e);
        }
    }

    @Override
    public void deregister(ServiceInstance instance) {
        try {
            InstanceDeregisterRequest request = new InstanceDeregisterRequest();
            
            // 设置服务信息
            request.setService(instance.getName());
            
            // 设置命名空间
            String namespace = instance.getNamespace();
            if (namespace != null && !namespace.isEmpty()) {
                request.setNamespace(namespace);
            } else {
                request.setNamespace("default");
            }
            
            // 设置host和port
            String host = instance.getHost();
            Integer port = instance.getPort();
            
            if (host != null) {
                request.setHost(host);
            }
            if (port != null) {
                request.setPort(port);
            }
            
            // 从metadata中获取token
            if (instance.getMetadata() != null) {
                String token = instance.getMetadata().get("token");
                if (token != null) {
                    request.setToken(token);
                }
            }
            
            // 执行注销
            providerAPI.deRegister(request);
            
        } catch (Exception e) {
            throw new RuntimeException("Failed to deregister service instance", e);
        }
    }

    @Override
    public void updateStatus(ServiceInstance instance, String status) {
        // Polaris通过心跳机制自动管理实例状态
        // 这里可以根据需要实现状态更新逻辑
        // 例如：如果状态为DOWN，可以临时注销实例；如果状态为UP，可以重新注册
        if ("DOWN".equalsIgnoreCase(status)) {
            deregister(instance);
        } else if ("UP".equalsIgnoreCase(status)) {
            register(instance);
        }
    }
}
